Skip to content

[ExecuTorch][WebGPU] Fuse attention QKV projections in prefill#21107

Merged
JCNTH merged 4 commits into
mainfrom
gh/JCNTH/52/orig
Jul 21, 2026
Merged

[ExecuTorch][WebGPU] Fuse attention QKV projections in prefill#21107
JCNTH merged 4 commits into
mainfrom
gh/JCNTH/52/orig

Conversation

@pytorchbot

Copy link
Copy Markdown
Collaborator

This PR was created by the merge bot to help merge the original PR into the main branch.
ghstack PR number: #20880 by @JCNTH
^ Please use this as the source of truth for the PR details, comments, and reviews
ghstack PR base: https://github.com/pytorch/executorch/tree/gh/JCNTH/52/base
ghstack PR head: https://github.com/pytorch/executorch/tree/gh/JCNTH/52/head
Merge bot PR base: https://github.com/pytorch/executorch/tree/main
Merge bot PR head: https://github.com/pytorch/executorch/tree/gh/JCNTH/52/orig

@diff-train-skip-merge

Pull Request resolved: #20880

Fuse the three attention q/k/v `linear_q4gsw` projections into one multi-output GEMM that scatter-writes q/k/v, removing the occupancy-starved small k/v dispatches in prefill on Llama-3.2-1B. Auto-applied graph pass, perplexity-neutral.

Problem

Attention lowers q/k/v as three separate `linear_q4gsw` GEMMs; the two N=512 k/v projections each dispatch a grid too small to fill the GPU, so they run occupancy-starved.

Solution

- Before: q/k/v = 3 GEMM dispatches (N=2048/512/512).
- After: one [2048->3072] multi-output GEMM that scatter-writes q/k/v to their own buffers, M-gated so it fires only at prefill (M>1) and keeps the three coop4 GEMVs at decode (M=1, where the fused 64x64 tile would waste 63/64 rows).

Implementation

- New standalone kernel `q4gsw_linear_gemm_qkv_fused.wgsl` (+ generated `_wgsl.h`); build-time pattern detection and an M-gated dispatch/resize hook in `WebGPUGraph::build`.
- q/k/v are repointed to fresh scratch buffers so the memory planner's reuse-aliasing cannot overlap the simultaneous fused write with a still-live input.
- The fused dispatch owns its one-off compute pipeline (released in the destructor), mirroring `q4gsw_linear_impl`.

Constraints

Auto-applied when the pattern matches (no flag): the detection gates on shader-f16, a 256-thread workgroup, and the Llama-3.2 GQA projection shape {2048, 512, 512} with no bias, so any graph without that triple gets the byte-identical baseline lowering.

Co-authored-with: Claude Code.
ghstack-source-id: 405251962
@exported-using-ghexport

Differential Revision: [D111489253](https://our.internmc.facebook.com/intern/diff/D111489253/)
@pytorch-bot

pytorch-bot Bot commented Jul 21, 2026

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/21107

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Jul 21, 2026
@github-actions

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

JCNTH added 2 commits July 21, 2026 14:10
Pull Request resolved: #20881

Fold the SwiGLU `sigmoid` + two `mul`s into a single elementwise pass computing (gate * sigmoid(gate)) * up, cutting the MLP activation traffic from ~8 units to ~3 on Llama-3.2-1B. Auto-applied graph pass, bit-exact.

Problem

The SwiGLU MLP lowers `silu(gate)*up` as three memory-bound elementwise dispatches (`sigmoid` -> `mul` -> `mul`) over the [S, 8192] intermediate.

Solution

- Before: `sigmoid` + 2 `mul`s (~8 tensor-traffic units over [S, 8192]).
- After: one `silu_mul_fused` pass computing `(g*sigmoid(g))*up` with the sigmoid in-register (~3 traffic units); the folded sigmoid + 1st-mul dispatches are dropped.

Implementation

- New standalone kernel `silu_mul_fused.wgsl` (+ generated `_wgsl.h`); build-time triple detection (requiring single-consumer sig/silu intermediates) + an in-place fused dispatch at the 2nd-mul anchor in `WebGPUGraph::build`.
- gate is repointed to a private pooled scratch buffer at its producer op, and the fused output to another, so the memory planner's reuse-aliasing (which places up_proj's output onto gate's dead slot) cannot stomp gate before the fused dispatch reads it; both pooled buffers are released after last use for cross-layer reuse.

Constraints

Auto-applied to fp32 elementwise triples with identical dims and single-consumer sig/silu intermediates (no flag); a graph without a matching triple gets the byte-identical baseline lowering. Stacked on the QKV-concat fusion diff.

Co-authored-with: Claude Code.
ghstack-source-id: 405251982
@exported-using-ghexport

Differential Revision: [D111489277](https://our.internmc.facebook.com/intern/diff/D111489277/)
… GEMM

Pull Request resolved: #20882

Read the activation tile as one `vec4<f32>` load instead of 4 scalar loads in the steel q4gsw prefill GEMM — a coalesced 16B fetch that shaves ~1-2% off prefill on Llama-3.2-1B (M4 Pro), bit-exact.

Problem

The steel GEMM staged the activation tile (As) with 4 scalar `t_input` reads per thread per BK step.

Solution

- Before: `As[...] = f16(t_input[base + 0/1/2/3])` — 4 scalar loads.
- After: `let av = t_input[base >> 2u]; As[...] = f16(av.x/y/z/w)` — one `vec4<f32>` load (16B coalesced); `t_input` is bound as `array<vec4<f32>>`.

Implementation

Applies across the shared steel template (base / f16 / pwdq / pwdqf16acc variants); generated `_wgsl.h` headers regenerated. Load-only — the vec4 output store was a measured wash on Apple (scalar-ALU) and is deliberately not included.

Constraints

Bit-exact (identical values — a wider load, not a math change). Requires the activation contiguous with K a multiple of 4, which holds for all Llama q4gsw projections.

Co-authored-with: Claude Code.
ghstack-source-id: 405251998
@exported-using-ghexport

Differential Revision: [D111500432](https://our.internmc.facebook.com/intern/diff/D111500432/)
@JCNTH
JCNTH self-requested a review July 21, 2026 21:10
@JCNTH
JCNTH merged commit 5828778 into main Jul 21, 2026
179 checks passed
@JCNTH
JCNTH deleted the gh/JCNTH/52/orig branch July 21, 2026 21:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants